<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" label-width="120px" size="small">
        <el-form-item prop="params.memberId">
          <el-input
            v-model="queryParams.params.memberId"
            class="filter-item"
            clearable
            placeholder="会员ID"
          />
        </el-form-item>
        <el-form-item prop="params.type">
          <el-select v-model="queryParams.params.templateId" clearable placeholder="优惠券">
            <el-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.purpose }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="params.couponType">
          <el-select v-model="queryParams.params.couponType" clearable placeholder="优惠券类型">
            <el-option v-for="item in couponTypeList" :key="item.id" :label="item.value" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="params.state">
          <el-select v-model="queryParams.params.state" clearable placeholder="优惠券状态">
            <el-option v-for="item in stateList" :key="item.id" :label="item.value" :value="item .code" />
          </el-select>
        </el-form-item>
        <el-form-item prop="startDate">
          <el-date-picker
            v-model="queryTime"
            end-placeholder="结束日期"
            range-separator="至"
            start-placeholder="开始日期"
            style="width: 100%"
            type="datetimerange"
            @change="queryTimeChangeHandler"
          />
        </el-form-item>
        <!-- 按钮 -->
        <el-button
          v-permission="['/coupon/record/search']"
          v-waves
          class="filter-item"
          icon="el-icon-search"
          size="small"
          style="margin-left: 10px;"
          type="primary"
          @click="getDataList"
        >查询
        </el-button>
        <el-button
          v-permission="['/coupon/record/search']"
          v-waves
          class="filter-item"
          icon="el-icon-refresh"
          size="small"
          type="primary"
          @click="resetQueryForm"
        >重置
        </el-button>
        <el-button
          v-permission="['/coupon/record/export']"
          v-waves
          class="filter-item"
          icon="el-icon-download"
          size="small"
          type="warning"
          @click="handleExport"
        >导出
        </el-button>
        <el-button
          v-permission="['/coupon/record/sendCoupon']"
          v-waves
          class="filter-item"
          icon="el-icon-s-ticket"
          size="small"
          type="success"
          @click="handleOpenDialog('sendCoupon')"
        >会员ID发券
        </el-button>
      </el-form>
    </div>
    <!-- 数据表格 -->
    <el-table
      v-loading="dataListLoading"
      :data="dataList"
      border
      fit
      highlight-current-row
      size="small"
      style="width: 100%;"
      @sort-change="handleSortChange"
    >
      <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
      <el-table-column align="center" label="券名称" prop="templateName" show-overflow-tooltip />
      <el-table-column align="center" label="券类型" prop="couponTypeName" show-overflow-tooltip sortable />
      <el-table-column align="center" label="会员ID" prop="memberId" show-overflow-tooltip sortable />
      <el-table-column align="center" label="会员名称" prop="memberName" show-overflow-tooltip sortable />
      <el-table-column align="center" label="优惠券状态" prop="stateName" show-overflow-tooltip sortable />
      <el-table-column align="center" label="开始时间" prop="startDate" show-overflow-tooltip sortable />
      <el-table-column align="center" label="结束时间" prop="endDate" show-overflow-tooltip sortable />
      <el-table-column align="center" label="发送时间" prop="sendTime" show-overflow-tooltip sortable />
      <el-table-column align="center" label="使用时间" prop="useTime" show-overflow-tooltip sortable />
      <el-table-column align="center" label="发送途径" prop="sendRouteName" show-overflow-tooltip />
      <el-table-column align="center" label="创建时间" prop="createdDate" show-overflow-tooltip sortable />
      <el-table-column align="center" label="编辑时间" prop="modifiedDate" show-overflow-tooltip sortable />
      <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip />
    </el-table>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.size"
        :page-sizes="[10,20,30, 50]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 发优惠券对话框 -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      element-loading-text="发放中"
      width="25%"
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        label-position="right"
        label-width="100px"
        size="small"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="会员ID：">
              <el-input
                v-model="dataForm.memberId"
                class="filter-item"
                clearable
                placeholder="会员ID"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="优惠券：" prop="templateId">
              <el-select v-model="dataForm.templateId" clearable placeholder="优惠券" style="width: 100%">
                <el-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.purpose }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发放数量：" prop="number">
              <el-input
                v-model="dataForm.number"
                class="filter-item"
                clearable
                placeholder="发放数量"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="券使用时间：" prop="startDate">
              <el-date-picker
                v-model="dateTime"
                end-placeholder="结束日期"
                range-separator="至"
                start-placeholder="开始日期"
                style="width: 100%"
                type="datetimerange"
                @change="dateChangeHandler"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：" prop="remark">
              <el-input
                v-model="dataForm.remark"
                :autosize="{ minRows: 2, maxRows: 4}"
                class="filter-item"
                clearable
                placeholder="备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus==='sendCoupon'" type="primary" @click="sendCoupon">发送</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { del, exportExcel, fetchList, sendCouponByPhone } from '@/api/coupon/record'
import { typeList } from '@/api/system/dict'
import { getTemplate } from '@/api/coupon/template'

var moment = require('moment')
export default {
  name: 'Record',
  data() {
    return {
      total: 0,
      couponTypeList: [],
      templateList: [], // 可用券列表
      stateList: [],
      dateTime: [],
      dataList: [],
      queryTime: [],
      dataListLoading: true,
      dialogFormVisible: false,
      dialogStatus: '',
      dialogLoading: false,
      dialogTitleMap: {
        add: '新增',
        update: '编辑'
      },
      // 查询参数对象
      queryParams: {
        page: 1,
        size: 10,
        params: {
          memberId: '',
          templateId: '',
          couponType: '',
          state: '',
          startDate: '',
          endDate: ''
        }
      },
      dataForm: {
        templateId: '',
        memberId: '',
        number: '',
        startDate: '',
        endDate: '',
        remark: ''
      },
      rules: {
        name: [{ required: true, message: '券名称不能为空', trigger: 'change' }],
        type: [{ required: true, message: '券类型不能为空', trigger: 'change' }],
        discountAmount: [{ required: true, message: '优惠金额不能为空', trigger: 'change' }],
        daysLimit: [{ required: true, message: '可用星期不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    formReadOnly() {
      return this.dialogStatus === 'view'
    }
  },
  mounted() {
    typeList({ type: 'couponType' }).then(res => {
      this.couponTypeList = res.data
    })
    typeList({ type: 'couponState' }).then(res => {
      this.stateList = res.data
    })
    getTemplate().then(res => {
      this.templateList = res.data
    })
    this.getDataList()
  },
  methods: {
    shownIndex(index) {
      return (this.queryParams.page - 1) * this.queryParams.size + index + 1
    },
    handleSortChange(data) {
      console.log('handleSortChange')
      console.log(data)
      if (data.order) {
        if (data.order.indexOf('asc') > -1) {
          this.queryParams.sortOrder = 'asc'
        } else {
          this.queryParams.sortOrder = 'desc'
        }
        this.queryParams.sortName = data.prop
      }
      console.log(this.queryParams)
      this.getDataList()
    },
    // 手动重置表单
    resetDataForm() {
      if (this.$refs['dataForm']) {
        // 由于编辑数据的时候会导致表单对象的初始化值发生变更，所以在重置表单前先手动重置表单对象的值
        this.dataForm = {
          templateId: '',
          memberId: '',
          number: '',
          startDate: '',
          endDate: '',
          remark: ''
        }
        this.$refs['dataForm'].resetFields()
        this.dateTime = []
      }
    },
    resetQueryForm() {
      this.$refs['queryForm'].resetFields()
      this.queryParams.page = 1
      this.queryTime = []
      this.queryParams.params.startDate = ''
      this.queryParams.params.endDate = ''
      this.getDataList()
    },
    getDataList() {
      this.dataListLoading = true
      fetchList(this.queryParams)
        .then(res => {
          console.log(res)
          this.dataList = res.data.records
          this.total = res.data.total
          this.dataListLoading = false
          this.$message.success(res.msg || '获取数据成功')
        })
        .catch(err => {
          console.log(err)
          this.dataListLoading = false
        })
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.getDataList()
    },
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getDataList()
    },
    handleOpenDialog(type, rowData) {
      // 表单状态为新增/编辑、打开新增/编辑窗口
      this.resetDataForm()
      this.dialogStatus = type
      this.dialogFormVisible = true
      if (type === 'update') {
        this.dataForm = JSON.parse(JSON.stringify(rowData))
      }
      if (rowData) {
        this.dataForm = JSON.parse(JSON.stringify(rowData))
        this.dateTime = [moment(this.dataForm.startDate), moment(this.dataForm.endDate)]
      }
    },
    sendCoupon() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          sendCouponByPhone(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '发送成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleDelete(rowData) {
      this.$confirm('是否删除该记录？', '删除提示', { type: 'warning' })
        .then(() => {
          del(rowData.id)
            .then(res => {
              console.log(res)
              // this.$message.success(res.msg || '删除成功')
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(cancel => {
          console.log(cancel)
        })
    },
    dateChangeHandler(value) {
      if (value) {
        this.dataForm.startDate = value[0]
        this.dataForm.endDate = value[1]
      }
    },
    queryTimeChangeHandler(value) {
      if (value) {
        this.queryParams.params.startDate = value[0]
        this.queryParams.params.endDate = value[1]
      }
    },
    handleExport() {
      console.log('handleExport')
      exportExcel(this.queryParams)
    }
  }
}
</script>
<style scoped>

.el-form-item {
  margin-bottom: 30px;
}

</style>
